/**
 * 
 */
package sg.edu.nus.iss.vmcs.payment;

import sg.edu.nus.iss.vmcs.price.PriceCalculator;
import sg.edu.nus.iss.vmcs.price.PricingContext;
import sg.edu.nus.iss.vmcs.system.MainController;

/**
 * @author moe
 * 
 */
public class NetsPayment implements Payment {

	private PaymentController paymentCtrl = null;
	private MainController mainCtrl = null;
	private NetsReader netsReader = null;
	private NetsInterfaceGateway netsGateway = null;
	
	private int amountToCollect = 0;
	private int amountCollected = 0;

	public NetsPayment(PaymentController paymentController, MainController mainCtrl){
		this.paymentCtrl = paymentController;
		this.mainCtrl = mainCtrl;
		netsReader = new NetsReader(this);
		netsGateway = new NetsInterfaceGateway(this);
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see sg.edu.nus.iss.vmcs.payment.Payment#completePayment(Boolean)
	 */
	public Boolean completePayment(Boolean status) {
		Boolean success = true;
		NetsUI netsUi = getPaymentController().getPanel().getNetsUI();
		netsUi.setActive(false);
		
		if (status){//Deduct amount
			success = netsGateway.deductMoney(amountToCollect);
			
			if (success){//successfully Deducted
				netsUi.setWarning(amountToCollect + " deducted");
			}else{
				netsUi.setWarning("Fail to Deduct");
			}
		}else{
			netsUi.setWarning(" ");
		}
		
		netsReader.ejectCard();
		
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sg.edu.nus.iss.vmcs.payment.Payment#processReceive(int)
	 */
	public void processReceive(int amount) {
		// TODO Auto-generated method stub

	}



	public void continueReceive(int amountToCollect) {
		// TODO Auto-generated method stub

	}
	
	private int calcPrice(int orgPrice){
		PricingContext ctx = new PricingContext();
		ctx.setPriceCalculator(PriceCalculator.NETS_PRICE_CALCULATOR);
		return ctx.getPrice(orgPrice);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sg.edu.nus.iss.vmcs.payment.Payment#startPayment(int, int)
	 */
	public void startPayment(int amountToCollect, int timeOutSec) {
		this.amountToCollect = calcPrice(amountToCollect);
		netsReader.acceptCard();
	}

	public void getCardInfo(NetsCardInfo info) {
		paymentCtrl.receivingPayment(this);//To indicate that payment made by NETS
		
		//Getting the Nets Card Information
		if (netsGateway.checkCard(info)){//Valid Card 
			paymentCtrl.processMoneyReceive(amountToCollect);
		}else{
//			paymentCtrl.refundPayment();
			paymentCtrl.processMoneyReceive(0);
			paymentCtrl.getPanel().getNetsUI().setWarning("Invalid Card");
		}
	}

	public PaymentController getPaymentController(){
		return paymentCtrl;
	}
	
	public NetsReader getNetsReader(){
		return netsReader;
	}
	
	public NetsInterfaceGateway getNetsGateway(){
		return netsGateway;
	}
	
	public void setActive(boolean b){
		getNetsReader().setActive(b);
	}
	
}
